import os
from ID3 import *
import dbus
from urllib import pathname2url


class SearchResult:
    
    def __init__(self, match):
        self.url = match[0].__str__()
        self.cat = match[1].__str__()
        self.ctype = match[2].__str__()
        self.name = os.path.basename(self.url)
        
    
    def __str__(self):
        return "Search Result " + self.url + " " + self.cat + " " + self.ctype


class Mp3(SearchResult):
    
    def __init__(self, match):
        SearchResult.__init__(self, match);
        id3 = ID3(self.url)
        try:
            self.title = id3['TITLE']
        except:
            pass
        try:
            self.artist = id3['ARTIST']
        except:
            pass
        
class Query:
    
    bus = dbus.SessionBus()
    obj = bus.get_object('org.freedesktop.Tracker','/org/freedesktop/tracker')
    
    #self.tracker = dbus.Interface(obj, 'org.freedesktop.Tracker')
    keywords_iface = dbus.Interface(obj, 'org.freedesktop.Tracker.Keywords')
    search_iface = dbus.Interface(obj, 'org.freedesktop.Tracker.Search')
    files_iface = dbus.Interface(obj, 'org.freedesktop.Tracker.Files')
        
        #self.version = self.tracker.GetVersion()

        #Self service eheheh
        #self.services = self.tracker.GetServices(True)
    services = ['Files','Development Files','Documents','Images','Music','Text Files','Videos']
    query_id = 0
    
    def __init__(self, query = None, filter = 'Files', offset = 0, max_hits = -1, byTag=False):
        self.query = query
        self.filter = filter
        self.offset = offset
        self.max_hits = max_hits
        self.byTag = byTag


class ResultSet:
    
    def __init__(self, query):
        self.query = query
        self.totalResults = -1
        

    def search(self):
        if self.query.byTag:
            self.returnedfiles = Query.keywords_iface.Search(-1,self.query.filter,[self.query.query,] ,self.query.offset,self.query.max_hits)
        else:
            self.returnedfiles = Query.search_iface.TextDetailed(1,self.query.filter,self.query.query,self.query.offset,self.query.max_hits)        

        self.count = len(self.returnedfiles)
        self.hasResults = self.count > 0
        if self.totalResults == -1:
            if self.query.byTag:
                total = Query.keywords_iface.Search(-1,self.query.filter,[self.query.query,] ,0,-1)
            else:
                total = Query.search_iface.TextDetailed(1,self.query.filter,self.query.query,0,-1)
            self.totalResults = len(total)
        
    def hasNext(self):
        return self.hasResults and self.query.offset + self.query.max_hits < self.totalResults
    
    def hasPrev(self):
        return self.hasResults and self.query.offset - self.query.max_hits >= 0
    
    def next(self):
        if self.hasNext(): 
            self.query.offset = self.query.offset + self.query.max_hits
            self.search()
        
    def prev(self):
        if self.hasPrev(): 
            self.query.offset = self.query.offset - self.query.max_hits
            self.search()
        
    def results(self):
        dict = {}
        for f in self.returnedfiles:
           if f[0].__str__().endswith('.mp3'):
               next = Mp3(f)
           else:
               next = SearchResult(f)
           if not dict.has_key(next.cat):
               dict[next.cat] = []
           dict[next.cat].append(next)
        return dict
    
    def tagByUrl(self, url, tags, service='Files'):
        Query.keywords_iface.Add(service, url, tags)
    
    def resultByUrl(self, url):
        for f in self.returnedfiles:
            if f[0].__str__() == url:
                if f[0].__str__().endswith('.mp3'):
                    return Mp3(f)
                else:
                    return SearchResult(f)
        return None

    def text_snippet(self, url, service='Files'):
        snippet = Query.search_iface.GetSnippet(service, url, self.query.query)
        if snippet == None:
            return "No snippet available"
        else:
            snippet = snippet.replace('<!--', '&lt;!--').strip()
            return snippet
        
    